package com.fubowen.lepton.ui.container.children.visited.recycler

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SortedList
import com.fubowen.lepton.bean.VisitedBean
import com.fubowen.lepton.databinding.FragmentVisitedItemBinding
import com.fubowen.lepton.extension.toTimeString
import com.fubowen.lepton.helper.ViewHelper.setIcon
import com.fubowen.lepton.helper.ViewHelper.setVisible


class VisitedAdapter(
    private val deleteIds: HashSet<Int>,
    private val onItemClickListener: OnItemClickListener
) : RecyclerView.Adapter<VisitedAdapter.ViewHolder>() {

    private var dataSource: SortedList<VisitedBean>? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = FragmentVisitedItemBinding.inflate(inflater, parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        dataSource?.apply {
            val item = get(position)
            holder.title.text = item.title
            holder.url.text = item.host
            holder.time.text = item.timestamp.toTimeString()
            holder.deleteOk.setVisible(deleteIds.contains(item.id))
            holder.icon.setIcon(item.icon, item.iconSource)
            holder.checkedGroup.setVisible(item.selectable)
        }
    }

    override fun getItemCount(): Int = dataSource?.size() ?: 0

    fun setDataSource(sortedList: SortedList<VisitedBean>) {
        dataSource = sortedList
    }

    inner class ViewHolder(
        binding: FragmentVisitedItemBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        val title = binding.visitedItemTitle
        val url = binding.visitedItemUrl
        val time = binding.visitedItemTime
        val icon = binding.visitedItemIcon
        private val delete = binding.visitedItemDelete
        val deleteOk = binding.visitedItemDeleteOk
        private val deleteCancel = binding.visitedItemDeleteCancel
        private val more = binding.visitedItemMore
        val checkedGroup = binding.visitedItemChecked

        init {
            onItemClickListener.apply {
                delete.setOnClickListener { onRemoveClick(itemView) }
                deleteOk.setOnClickListener { onRemoveOkClick(itemView) }
                deleteCancel.setOnClickListener { onRemoveCancelClick(itemView) }
                more.setOnClickListener { onMoreMenuClick(itemView) }
                itemView.setOnClickListener { onClick(itemView) }
                itemView.setOnLongClickListener {
                    onMoreMenuClick(itemView)
                    true
                }
            }
        }
    }
}